"""
BossAgent工具实现
"""

import json
import subprocess
import os
from datetime import datetime
from .registry import register_tool
import logging

logger = logging.getLogger(__name__)

class BossAgentTools:
    def __init__(self):
        self.script_dir = "/tmp/mcp_scripts"   # 脚本存储目录
        os.makedirs(self.script_dir, exist_ok=True)
    
    def process_llm_solutions(self, solutions_data):
        """处理LLM返回的解决方案"""
        solutions = solutions_data.get("solutions", [])
        results = []
        
        for solution in solutions:
            result = self._process_single_solution(solution)
            results.append(result)
        
        return {
            "status": "success",
            "processed_solutions": len(solutions),
            "results": results
        }
    
    def _process_single_solution(self, solution):
        """处理单个解决方案"""
        solution_id = solution.get("id")
        content = solution.get("content", {})
        tools_required = content.get("tools_required", {})
        
        # 为每个节点生成脚本
        scripts = {}
        for node_name, tools in tools_required.items():
            script_content = self._generate_node_script(node_name, tools, content)
            script_path = f"{self.script_dir}/solution_{solution_id}_{node_name}.sh"
            
            with open(script_path, 'w', encoding='utf-8') as f:
                f.write(script_content)
            
            scripts[node_name] = script_path
        
        return {
            "solution_id": solution_id,
            "scripts_generated": scripts,
            "status": "ready_for_execution"
        }
    
    def _generate_node_script(self, node_name, tools, content):
        """根据节点和工具生成脚本"""
        root_cause = content.get("root_cause_analysis", "")
        description = content.get("description", "")
        
        script = f'''#!/bin/bash
# 节点: {node_name}
# 根因分析: {root_cause}
# 描述: {description}

echo "=== 开始执行 {node_name} 节点诊断 ==="
echo "时间: $(date)"
echo "根因分析: {root_cause}"
echo ""

'''
        
        # 根据工具类型生成不同的脚本内容
        for tool in tools:
            if tool == "cpu_analysis":
                script += self._generate_cpu_script()
            elif tool == "memory_analysis":
                script += self._generate_memory_script()
            elif tool == "system_analysis":
                script += self._generate_system_script()
            elif tool == "network_analysis":
                script += self._generate_network_script()
        
        script += '''
echo "=== 诊断完成 ==="
echo "时间: $(date)"
'''
        
        return script
    
    def _generate_cpu_script(self):
        """生成CPU分析脚本"""
        return '''
# CPU分析
echo "--- CPU分析 ---"
echo "CPU使用率:"
top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d'%' -f1

echo "CPU负载:"
uptime

echo "TOP5 CPU进程:"
ps aux --sort=-%cpu | head -6

echo "CPU核心数:"
nproc

echo "CPU温度(如果可用):"
if command -v sensors &> /dev/null; then
    sensors | grep -i temp
else
    echo "sensors命令不可用"
fi
'''
    
    def _generate_memory_script(self):
        """生成内存分析脚本"""
        return '''
# 内存分析
echo "--- 内存分析 ---"
echo "内存使用情况:"
free -h

echo "内存详细信息:"
cat /proc/meminfo | grep -E "(MemTotal|MemFree|MemAvailable|Buffers|Cached)"

echo "TOP5 内存进程:"
ps aux --sort=-%mem | head -6

echo "交换分区使用:"
swapon --show
'''
    
    def _generate_system_script(self):
        """生成系统分析脚本"""
        return '''
# 系统分析
echo "--- 系统分析 ---"
echo "系统信息:"
uname -a

echo "系统负载:"
uptime

echo "磁盘使用情况:"
df -h

echo "进程数量:"
ps aux | wc -l

echo "系统运行时间:"
uptime -p
'''
    
    def _generate_network_script(self):
        """生成网络分析脚本"""
        return '''
# 网络分析
echo "--- 网络分析 ---"
echo "网络接口:"
ip addr show

echo "网络连接:"
netstat -tuln

echo "网络统计:"
ss -s
'''

# 注册工具
boss_tools = BossAgentTools()

async def process_llm_solutions_impl(arguments):
    """处理LLM解决方案的实现函数"""
    solutions_data = arguments.get("solutions_data", {})
    return [{"text": str(boss_tools.process_llm_solutions(solutions_data))}]

register_tool(
    "process_llm_solutions", 
    "处理LLM返回的解决方案并生成诊断脚本",
    {
        "type": "object",
        "properties": {
            "solutions_data": {
                "type": "object",
                "description": "LLM返回的解决方案数据"
            }
        },
        "required": ["solutions_data"]
    },
    process_llm_solutions_impl
)